/*
 *  Copyright (C) 2011 glauco
 * 
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 * 
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 * 
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package org.balisunrise.swing.components;

import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import javax.swing.JComponent;
import javax.swing.event.AncestorEvent;
import javax.swing.event.AncestorListener;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import org.balisunrise.application.Application;
import org.balisunrise.builder.CommonFactory;
import org.balisunrise.builder.FactoryException;
import org.balisunrise.common.Binding;
import org.balisunrise.common.FieldInput;
import org.balisunrise.common.Messenger;
import org.balisunrise.common.SyncResult;
import org.balisunrise.common.defaults.DefaultEvent;
import org.balisunrise.common.defaults.VEAUtil;
import org.balisunrise.common.events.GotFocusEvent;
import org.balisunrise.common.events.LostFocusEvent;
import org.balisunrise.common.events.SyncEvent;
import org.balisunrise.common.listeners.BindingListener;
import org.balisunrise.common.listeners.FieldInputListener;
import org.balisunrise.swing.components.focusManager.FocusManagerListener;
import org.balisunrise.swing.components.focusManager.FocusManagers;
import org.balisunrise.swing.components.focusManager.FocusTraversalEvent;
import org.balisunrise.swing.components.focusManager.JPanelFocusManager;

/**
 *
 * @author glauco
 */
public class FieldInputUtil implements FocusListener, BindingListener,
        DocumentListener, AncestorListener, FocusManagerListener {

    private FieldInput<? extends JComponent> fieldInput;
    private List<FieldInputListener> inputListeners;
    private JPanelFocusManager manager;
    private Messenger messenger;

    public FieldInputUtil(FieldInput<? extends JComponent> fieldInput) {
        this.fieldInput = fieldInput;
        this.inputListeners = new ArrayList<FieldInputListener>();
    }

    public List<FieldInputListener> getInputListeners() {
        return inputListeners;
    }

    public void setInputListeners(List<FieldInputListener> inputListeners) {
        this.inputListeners = inputListeners;
    }

    public JPanelFocusManager getManager() {
        return manager;
    }

    public void setManager(JPanelFocusManager manager) {
        if(manager == this.manager)
            return ;

        if(this.manager != null)
            this.manager.removeFocusManagerListener(this);
        if(manager != null)
            manager.addFocusManagerListener(this);

        this.manager = manager;

    }

    public Messenger getMessenger(){
        if(messenger == null)
            messenger = VEAUtil.getMessenger(fieldInput);
        return messenger;
    }

    private String getId(){
        return fieldInput.getName();
    }

    // FocusListener
    @Override
    public void focusGained(FocusEvent e) {
        try{
            GotFocusEvent evt = CommonFactory.getFactory()
                    .createGotFocusEvent(fieldInput);
            for (FieldInputListener fil : inputListeners) {
                fil.gotFocus(evt);
            }
            fieldInput.getOwner().actionPerformed(evt);
        }catch(FactoryException ex){
            Application.get().getLogger().log(Level.SEVERE,
                    "FieldInputUtil não pode criar GotFocusEvent", ex);
        }
    }

    @Override
    public void focusLost(FocusEvent e) {
        try{
            LostFocusEvent evt = CommonFactory.getFactory()
                    .createLostFocusEvent(fieldInput);
            for (FieldInputListener fil : inputListeners) {
                fil.lostFocus(null);
            }
            fieldInput.getOwner().actionPerformed(evt);
        }catch(FactoryException ex){
            Application.get().getLogger().log(Level.SEVERE,
                    "FieldInputUtil não pode criar LostFocusEvent", ex);
        }
    }

    // BindingListener
    @Override
    public void becameBound(Binding bndng) { }

    @Override
    public void becameUnbound(Binding bndng) { }

    @Override
    public void synced(SyncResult sr) {

        if (sr.getSyncType() == SyncResult.SyncType.TARGET_TO_SOURCE ){

            Messenger m = getMessenger();

            switch (sr.getResultType()) {
                case SUCCESS:
                    if(m != null)
                        m.removeMessage(getId());
                    break;
                case FAILURE:
                    //System.out.println("Sync Failed: " + sync.getCause() + " : "
                    //        + sync.getNewPropertyValue());
                    break;
                case EXCEPTION:
                    if(m != null)
                        m.addMessage(getId(), sr.getExceptionMessage(),
                                Messenger.ERROR);
                    else
                        Application.get().getLogger().log(Level.SEVERE,
                                "FieldInputUtil disparou uma erro de "
                                + "sincronização dos campos, o qual não foi"
                                + "enviado ao Messenger: "
                                + sr.getExceptionMessage());
                    break;
            }
        }
        
        try{
            SyncEvent evt = CommonFactory.getFactory()
                    .createSyncEvent(fieldInput, sr);
            for (FieldInputListener fil : inputListeners) {
                fil.afterSync(null);
            }
            fieldInput.getOwner().actionPerformed(evt);
        }catch(FactoryException ex){
            Application.get().getLogger().log(Level.SEVERE,
                    "FieldInputUtil não pode criar SyncEvent", ex);

        }
    }

    //DocumentListener
    @Override
    public void insertUpdate(DocumentEvent e) {
        valueChaged();
    }

    @Override
    public void removeUpdate(DocumentEvent e) {
        valueChaged();
    }

    @Override
    public void changedUpdate(DocumentEvent e) {
        valueChaged();
    }

    private void valueChaged(){
        DefaultEvent evt = new DefaultEvent("ValueChanged", fieldInput);
        for (FieldInputListener fil : inputListeners) {
            fil.valueChanged(evt);
        }
        fieldInput.getOwner().actionPerformed(evt);
    }

    // AncestorListener
    @Override
    public void ancestorAdded(AncestorEvent event) {
        JPanelFocusManager focusManager =
                FocusManagers.getInstance()
                .getFocusManager(event.getComponent());
        if(focusManager != null)
            setManager(focusManager);
    }

    @Override
    public void ancestorRemoved(AncestorEvent event) {
        JPanelFocusManager focusManager =
                FocusManagers.getInstance()
                .getFocusManager(event.getComponent());
        if(focusManager == null)
            setManager(null);
    }

    @Override
    public void ancestorMoved(AncestorEvent event) {
        ancestorAdded(event);
    }

    // FocusManagerListener
    @Override
    public void focusTravesed(FocusTraversalEvent evt) {
        if(! evt.isTraversedToDown())
            return ;
        if(evt.getTraversedComponents().contains(fieldInput.getVisualRepresentation()))
            try{
                org.balisunrise.common.events.FocusTraversalEvent e =
                        CommonFactory.getFactory()
                        .createFocusTraversalEvent(fieldInput);
                for (FieldInputListener listener : inputListeners) {
                    listener.focusTraversal(e);
                }
                fieldInput.getOwner().actionPerformed(e);
            }catch(FactoryException ex){
                Application.get().getLogger().log(Level.SEVERE,
                        "FieldInputUtil não pode criar FocusTraversalEvent",
                        ex);
            }
    }
}
